package org.csu.measure.controller;

import org.csu.measure.service.GetData;
import org.csu.measure.domain.CKMetrics;
import org.csu.measure.domain.Class;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/toCK")
@SessionAttributes(value = {"toCK"})
public class CKController {

    //跳转到CK界面
    @GetMapping("/goToCKMetrics")
    public String signonForm(Model model){
        return "CKMetric";
    }
    @PostMapping("/getClassList")
    public String getClassList(Model model, HttpSession session, @RequestParam("code")String code) throws IOException {
        String dir = "test.xml";
        File file = new File(dir);
//如果文件不存在，创建文件
        if (!file.exists())
            file.createNewFile();
        //创建FileWriter对象
        FileWriter writer = new FileWriter(file);
        //向文件中写入内容
        writer.write(code);
        writer.flush();
        writer.close();

        GetData data = new GetData();
        List<Class> classList = new ArrayList<>();
        classList = data.getData();

        ArrayList<CKMetrics> ckList = new ArrayList<>();
        for(int i = 0; i < classList.size(); i++){
            ckList.add(classList.get(i).getCk());
        }

        model.addAttribute("classList", classList);
        session.setAttribute("ckList",ckList);
        model.addAttribute("code", code);

        return "CKMetric";
    }

    @PostMapping("/setLine")
    @ResponseBody
    public ArrayList<CKMetrics> setLine(HttpSession session) {
        ArrayList<CKMetrics> ckList = (ArrayList<CKMetrics>)session.getAttribute("ckList");
        return ckList;
    }

}
